using System;

namespace StateManagement.Models {
 public class Cart<T> where T : Product {
    private List<CartItem<T>> items = new List<CartItem<T>>();
    public void Add(T product, uint quantity = 1) {
      CartItem<T> cartItem = this[product];
      if (cartItem == null) items.Add(new CartItem<T>(product, quantity));
      else cartItem.Increase(quantity);
    }
    public void Remove(T product, uint quantity = 1) {
      CartItem<T> cartItem = this[product];
      if (cartItem != null) {
        if (cartItem.Decrease(quantity)) {
          if (cartItem.Quantity == 0) items.Remove(cartItem);
        }
      }
    }
    public float GrandTotal {
      get {
        float total = 0.0F;
        foreach (var ci in items) total += ci.SubTotal;
        return total;
      }
    }
    public CartItem<T> this[int i] {
      get {
        if ((i < 0) || (i >= items.Count)) return null;
        return items[i];
      }
    }
    public CartItem<T> this[T product] {
      get {
        return items.FirstOrDefault(ci => (ci.Product == product));
      }
    }
    public IEnumerable<CartItem<T>> All {
      get {
        foreach (var item in items) yield return item;
      }
    }

    public int Count {  get { return items.Count; } }
  }
}
